import json


class JsonPlaceholderReplacer:
    def __init__(self, json_data):
        # 将 JSON 字符串解析为 Python 字典
        self.json_data = json.loads(json_data) if isinstance(json_data, str) else json_data

    def replace_placeholders(self, replacements):
        """
        使用一个包含占位符和对应值的字典批量替换 JSON 数据中的占位符。
        :param replacements: dict, 包含 {占位符: 值} 的键值对
        """
        for placeholder, value in replacements.items():
            self._replace_recursive(self.json_data, placeholder, value)

    def replace_placeholder(self, key, value):
        self._replace_recursive(self.json_data, key, value)

    def _replace_recursive(self, data, placeholder, value):
        """递归地遍历和替换 JSON 数据中的占位符"""
        if isinstance(data, dict):
            for key, val in list(data.items()):
                if isinstance(val, (dict, list)):
                    self._replace_recursive(val, placeholder, value)
                elif val == placeholder:
                    # 如果值完全匹配占位符，将其替换为对象或列表
                    data[key] = value
        elif isinstance(data, list):
            for index, item in enumerate(data):
                if isinstance(item, (dict, list)):
                    self._replace_recursive(item, placeholder, value)
                elif item == placeholder:
                    # 如果列表中的项完全匹配占位符，将其替换为对象或列表
                    data[index] = value

    def get_modified_json(self):
        """返回替换后的 JSON 字符串"""
        return json.dumps(self.json_data, ensure_ascii=False, indent=4)
